"""
用户管理系统模块
包含用户注册、登录、个人中心等功能
"""

import json
import hashlib
import uuid
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any
from pathlib import Path
import streamlit as st


class UserManager:
    """用户管理类"""
    
    def __init__(self, data_file: str = "users_data.json"):
        """初始化用户管理器"""
        self.data_file = Path(data_file)
        self.users_data = self._load_users_data()
        self.orders_data = self._load_orders_data()
    
    def _load_users_data(self) -> Dict[str, Any]:
        """加载用户数据"""
        if self.data_file.exists():
            try:
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except (json.JSONDecodeError, FileNotFoundError):
                pass
        
        # 创建默认用户数据结构
        default_data = {
            "users": {},
            "sessions": {},
            "created_at": datetime.now().isoformat()
        }
        self._save_users_data(default_data)
        return default_data
    
    def _load_orders_data(self) -> Dict[str, Any]:
        """加载订单数据"""
        orders_file = Path("orders_data.json")
        if orders_file.exists():
            try:
                with open(orders_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except (json.JSONDecodeError, FileNotFoundError):
                pass
        
        # 创建默认订单数据（示例数据）
        default_orders = {
            "orders": {
                "user@example.com": [
                    {
                        "order_id": "2024070300001",
                        "status": "已发货",
                        "total_amount": 1299.00,
                        "items": ["智能手机 x1", "手机壳 x1"],
                        "tracking_number": "SF1234567890",
                        "estimated_delivery": "2024-07-06",
                        "created_at": "2024-07-03 10:30:00",
                        "updated_at": "2024-07-04 09:15:00"
                    },
                    {
                        "order_id": "2024070200001",
                        "status": "已送达",
                        "total_amount": 599.00,
                        "items": ["蓝牙耳机 x1"],
                        "tracking_number": "SF0987654321",
                        "estimated_delivery": "2024-07-04",
                        "created_at": "2024-07-02 14:20:00",
                        "updated_at": "2024-07-04 16:30:00"
                    }
                ],
                "demo@test.com": [
                    {
                        "order_id": "2024070300002",
                        "status": "配送中",
                        "total_amount": 2999.00,
                        "items": ["笔记本电脑 x1"],
                        "tracking_number": "YTO1122334455",
                        "estimated_delivery": "2024-07-07",
                        "created_at": "2024-07-03 16:45:00",
                        "updated_at": "2024-07-04 08:20:00"
                    }
                ]
            }
        }
        
        with open(orders_file, 'w', encoding='utf-8') as f:
            json.dump(default_orders, f, ensure_ascii=False, indent=2)
        
        return default_orders
    
    def _save_users_data(self, data: Dict[str, Any]):
        """保存用户数据"""
        with open(self.data_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
    
    def _save_orders_data(self):
        """保存订单数据"""
        orders_file = Path("orders_data.json")
        with open(orders_file, 'w', encoding='utf-8') as f:
            json.dump(self.orders_data, f, ensure_ascii=False, indent=2)
    
    def _hash_password(self, password: str) -> str:
        """密码哈希"""
        return hashlib.sha256(password.encode()).hexdigest()
    
    def register_user(self, username: str, email: str, password: str, phone: str = "") -> Dict[str, Any]:
        """用户注册"""
        if email in self.users_data["users"]:
            return {"success": False, "message": "该邮箱已注册"}
        
        # 检查用户名是否重复
        for user_data in self.users_data["users"].values():
            if user_data["username"] == username:
                return {"success": False, "message": "用户名已存在"}
        
        # 创建新用户
        user_id = str(uuid.uuid4())
        user_data = {
            "user_id": user_id,
            "username": username,
            "email": email,
            "password": self._hash_password(password),
            "phone": phone,
            "created_at": datetime.now().isoformat(),
            "last_login": None,
            "profile": {
                "avatar": "👤",
                "nickname": username,
                "gender": "",
                "birthday": "",
                "address": ""
            },
            "preferences": {
                "notification": True,
                "marketing": False,
                "theme": "default"
            }
        }
        
        self.users_data["users"][email] = user_data
        self._save_users_data(self.users_data)
        
        # 为新用户创建示例订单
        if email not in self.orders_data["orders"]:
            self.orders_data["orders"][email] = []
            self._save_orders_data()
        
        return {"success": True, "message": "注册成功", "user_id": user_id}
    
    def login_user(self, email: str, password: str) -> Dict[str, Any]:
        """用户登录"""
        if email not in self.users_data["users"]:
            return {"success": False, "message": "用户不存在"}
        
        user_data = self.users_data["users"][email]
        if user_data["password"] != self._hash_password(password):
            return {"success": False, "message": "密码错误"}
        
        # 更新最后登录时间
        user_data["last_login"] = datetime.now().isoformat()
        self._save_users_data(self.users_data)
        
        # 创建会话
        session_id = str(uuid.uuid4())
        session_data = {
            "user_email": email,
            "created_at": datetime.now().isoformat(),
            "expires_at": (datetime.now() + timedelta(hours=24)).isoformat()
        }
        
        self.users_data["sessions"][session_id] = session_data
        self._save_users_data(self.users_data)
        
        return {
            "success": True,
            "message": "登录成功",
            "session_id": session_id,
            "user_data": {
                "user_id": user_data["user_id"],
                "username": user_data["username"],
                "email": email,
                "profile": user_data["profile"]
            }
        }
    
    def logout_user(self, session_id: str) -> Dict[str, Any]:
        """用户登出"""
        if session_id in self.users_data["sessions"]:
            del self.users_data["sessions"][session_id]
            self._save_users_data(self.users_data)
            return {"success": True, "message": "登出成功"}
        return {"success": False, "message": "会话不存在"}
    
    def validate_session(self, session_id: str) -> Dict[str, Any]:
        """验证会话"""
        if session_id not in self.users_data["sessions"]:
            return {"valid": False, "message": "会话不存在"}
        
        session_data = self.users_data["sessions"][session_id]
        expires_at = datetime.fromisoformat(session_data["expires_at"])
        
        if datetime.now() > expires_at:
            # 会话过期，删除
            del self.users_data["sessions"][session_id]
            self._save_users_data(self.users_data)
            return {"valid": False, "message": "会话已过期"}
        
        user_email = session_data["user_email"]
        user_data = self.users_data["users"][user_email]
        
        return {
            "valid": True,
            "user_data": {
                "user_id": user_data["user_id"],
                "username": user_data["username"],
                "email": user_email,
                "profile": user_data["profile"]
            }
        }
    
    def get_user_orders(self, email: str) -> List[Dict[str, Any]]:
        """获取用户订单"""
        return self.orders_data["orders"].get(email, [])
    
    def get_order_by_id(self, order_id: str, email: str) -> Optional[Dict[str, Any]]:
        """根据订单ID获取订单详情"""
        user_orders = self.get_user_orders(email)
        for order in user_orders:
            if order["order_id"] == order_id:
                return order
        return None
    
    def update_user_profile(self, email: str, profile_data: Dict[str, Any]) -> Dict[str, Any]:
        """更新用户资料"""
        if email not in self.users_data["users"]:
            return {"success": False, "message": "用户不存在"}
        
        user_data = self.users_data["users"][email]
        user_data["profile"].update(profile_data)
        self._save_users_data(self.users_data)
        
        return {"success": True, "message": "资料更新成功"}
    
    def change_password(self, email: str, old_password: str, new_password: str) -> Dict[str, Any]:
        """修改密码"""
        if email not in self.users_data["users"]:
            return {"success": False, "message": "用户不存在"}
        
        user_data = self.users_data["users"][email]
        if user_data["password"] != self._hash_password(old_password):
            return {"success": False, "message": "原密码错误"}
        
        user_data["password"] = self._hash_password(new_password)
        self._save_users_data(self.users_data)
        
        return {"success": True, "message": "密码修改成功"}
    
    def get_user_stats(self, email: str) -> Dict[str, Any]:
        """获取用户统计信息"""
        user_orders = self.get_user_orders(email)
        
        total_orders = len(user_orders)
        total_amount = sum(order["total_amount"] for order in user_orders)
        
        status_counts = {}
        for order in user_orders:
            status = order["status"]
            status_counts[status] = status_counts.get(status, 0) + 1
        
        return {
            "total_orders": total_orders,
            "total_amount": total_amount,
            "status_distribution": status_counts,
            "recent_orders": user_orders[-5:] if user_orders else []
        }


# 创建全局用户管理器实例
@st.cache_resource
def get_user_manager():
    """获取用户管理器实例"""
    return UserManager()


def init_user_session():
    """初始化用户会话状态"""
    if "user_logged_in" not in st.session_state:
        st.session_state.user_logged_in = False
    if "user_data" not in st.session_state:
        st.session_state.user_data = None
    if "session_id" not in st.session_state:
        st.session_state.session_id = None
    if "show_login_modal" not in st.session_state:
        st.session_state.show_login_modal = False


def check_login_status():
    """检查登录状态"""
    if st.session_state.session_id:
        user_manager = get_user_manager()
        session_result = user_manager.validate_session(st.session_state.session_id)
        
        if session_result["valid"]:
            st.session_state.user_logged_in = True
            st.session_state.user_data = session_result["user_data"]
            return True
        else:
            # 会话无效，清除状态
            st.session_state.user_logged_in = False
            st.session_state.user_data = None
            st.session_state.session_id = None
            return False
    return False


def render_login_interface():
    """渲染登录界面"""
    user_manager = get_user_manager()
    
    # 创建两个标签页：登录和注册
    login_tab, register_tab = st.tabs(["🔐 登录", "📝 注册"])
    
    with login_tab:
        st.markdown("### 用户登录")
        
        with st.form("login_form"):
            email = st.text_input("邮箱", placeholder="请输入您的邮箱地址")
            password = st.text_input("密码", type="password", placeholder="请输入密码")
            
            col1, col2 = st.columns(2)
            with col1:
                login_submitted = st.form_submit_button("🔐 登录", type="primary", use_container_width=True)
            with col2:
                if st.form_submit_button("🔄 清空", use_container_width=True):
                    st.rerun()
            
            if login_submitted:
                if email and password:
                    result = user_manager.login_user(email, password)
                    if result["success"]:
                        st.session_state.user_logged_in = True
                        st.session_state.user_data = result["user_data"]
                        st.session_state.session_id = result["session_id"]
                        st.session_state.show_login_modal = False
                        st.success("登录成功！")
                        st.rerun()
                    else:
                        st.error(result["message"])
                else:
                    st.warning("请填写完整信息")
    
    with register_tab:
        st.markdown("### 用户注册")
        
        with st.form("register_form"):
            reg_username = st.text_input("用户名", placeholder="请输入用户名")
            reg_email = st.text_input("邮箱", placeholder="请输入邮箱地址")
            reg_password = st.text_input("密码", type="password", placeholder="请设置密码")
            reg_password_confirm = st.text_input("确认密码", type="password", placeholder="请再次输入密码")
            reg_phone = st.text_input("手机号", placeholder="请输入手机号（可选）")
            
            col1, col2 = st.columns(2)
            with col1:
                register_submitted = st.form_submit_button("📝 注册", type="primary", use_container_width=True)
            with col2:
                if st.form_submit_button("🔄 清空", use_container_width=True):
                    st.rerun()
            
            if register_submitted:
                if reg_username and reg_email and reg_password and reg_password_confirm:
                    if reg_password != reg_password_confirm:
                        st.error("两次输入的密码不一致")
                    elif len(reg_password) < 6:
                        st.error("密码长度至少6位")
                    else:
                        result = user_manager.register_user(reg_username, reg_email, reg_password, reg_phone)
                        if result["success"]:
                            st.success("注册成功！请切换到登录标签页进行登录。")
                        else:
                            st.error(result["message"])
                else:
                    st.warning("请填写完整信息")


def render_user_profile_menu():
    """渲染用户资料菜单"""
    if not st.session_state.user_logged_in:
        return
    
    user_data = st.session_state.user_data
    
    # 用户头像和名称
    profile_avatar = user_data.get("profile", {}).get("avatar", "👤")
    username = user_data.get("username", "用户")
    
    st.markdown(f"### {profile_avatar} {username}")
    
    # 菜单选项
    menu_options = ["个人信息", "我的订单", "账户设置", "退出登录"]
    selected_menu = st.selectbox("选择功能", menu_options, key="profile_menu")
    
    if selected_menu == "个人信息":
        render_user_info()
    elif selected_menu == "我的订单":
        render_user_orders()
    elif selected_menu == "账户设置":
        render_account_settings()
    elif selected_menu == "退出登录":
        if st.button("确认退出", type="primary", use_container_width=True):
            user_manager = get_user_manager()
            user_manager.logout_user(st.session_state.session_id)
            
            # 清除会话状态
            st.session_state.user_logged_in = False
            st.session_state.user_data = None
            st.session_state.session_id = None
            st.success("已退出登录")
            st.rerun()


def render_user_info():
    """渲染用户信息页面"""
    st.markdown("#### 👤 个人信息")
    
    user_data = st.session_state.user_data
    email = user_data.get("email", "")
    
    user_manager = get_user_manager()
    user_stats = user_manager.get_user_stats(email)
    
    # 用户统计信息
    col1, col2, col3 = st.columns(3)
    with col1:
        st.metric("总订单数", user_stats["total_orders"])
    with col2:
        st.metric("总消费金额", f"¥{user_stats['total_amount']:.2f}")
    with col3:
        pending_orders = user_stats["status_distribution"].get("待发货", 0) + \
                        user_stats["status_distribution"].get("已发货", 0) + \
                        user_stats["status_distribution"].get("配送中", 0)
        st.metric("待收货订单", pending_orders)
    
    st.divider()
    
    # 个人资料编辑
    st.markdown("#### ✏️ 编辑资料")
    
    profile = user_data.get("profile", {})
    
    with st.form("profile_form"):
        new_nickname = st.text_input("昵称", value=profile.get("nickname", ""))
        new_avatar = st.selectbox("头像", ["👤", "👨", "👩", "🙋‍♂️", "🙋‍♀️", "👨‍💼", "👩‍💼"], 
                                index=0 if profile.get("avatar", "👤") == "👤" else 1)
        new_gender = st.selectbox("性别", ["", "男", "女"], 
                                index=0 if not profile.get("gender") else (1 if profile.get("gender") == "男" else 2))
        new_birthday = st.date_input("生日", value=None)
        new_address = st.text_area("地址", value=profile.get("address", ""), height=100)
        
        if st.form_submit_button("💾 保存修改", type="primary"):
            profile_data = {
                "nickname": new_nickname,
                "avatar": new_avatar,
                "gender": new_gender,
                "birthday": new_birthday.isoformat() if new_birthday else "",
                "address": new_address
            }
            
            result = user_manager.update_user_profile(email, profile_data)
            if result["success"]:
                st.success("资料更新成功！")
                # 更新会话中的用户数据
                st.session_state.user_data["profile"].update(profile_data)
                st.rerun()
            else:
                st.error(result["message"])


def render_user_orders():
    """渲染用户订单页面"""
    st.markdown("#### 📦 我的订单")
    
    user_data = st.session_state.user_data
    email = user_data.get("email", "")
    
    user_manager = get_user_manager()
    orders = user_manager.get_user_orders(email)
    
    if not orders:
        st.info("您还没有任何订单")
        return
    
    # 订单筛选
    col1, col2 = st.columns([2, 1])
    with col1:
        status_filter = st.selectbox("筛选状态", ["全部", "待发货", "已发货", "配送中", "已送达", "已取消"])
    with col2:
        sort_order = st.selectbox("排序方式", ["最新订单", "最早订单", "金额从高到低", "金额从低到高"])
    
    # 过滤订单
    filtered_orders = orders
    if status_filter != "全部":
        filtered_orders = [order for order in orders if order["status"] == status_filter]
    
    # 排序订单
    if sort_order == "最新订单":
        filtered_orders = sorted(filtered_orders, key=lambda x: x["created_at"], reverse=True)
    elif sort_order == "最早订单":
        filtered_orders = sorted(filtered_orders, key=lambda x: x["created_at"])
    elif sort_order == "金额从高到低":
        filtered_orders = sorted(filtered_orders, key=lambda x: x["total_amount"], reverse=True)
    elif sort_order == "金额从低到高":
        filtered_orders = sorted(filtered_orders, key=lambda x: x["total_amount"])
    
    # 显示订单
    for order in filtered_orders:
        with st.expander(f"📦 订单 {order['order_id']} - {order['status']} - ¥{order['total_amount']:.2f}"):
            col1, col2 = st.columns([2, 1])
            
            with col1:
                st.markdown("**📋 订单信息**")
                st.write(f"订单号：`{order['order_id']}`")
                st.write(f"订单状态：**{order['status']}**")
                st.write(f"订单金额：**¥{order['total_amount']:.2f}**")
                st.write(f"下单时间：{order['created_at']}")
                st.write(f"更新时间：{order['updated_at']}")
                
                st.markdown("**🛍️ 商品清单**")
                for item in order['items']:
                    st.write(f"- {item}")
            
            with col2:
                st.markdown("**🚚 物流信息**")
                st.write(f"物流单号：`{order['tracking_number']}`")
                st.write(f"预计送达：{order['estimated_delivery']}")
                
                # 订单操作按钮
                if order['status'] == "待发货":
                    if st.button("❌ 取消订单", key=f"cancel_{order['order_id']}"):
                        st.warning("取消订单功能开发中...")
                elif order['status'] == "已送达":
                    if st.button("⭐ 评价订单", key=f"review_{order['order_id']}"):
                        st.info("评价功能开发中...")
                elif order['status'] in ["已发货", "配送中"]:
                    if st.button("🚚 查看物流", key=f"track_{order['order_id']}"):
                        st.info("物流跟踪功能开发中...")


def render_account_settings():
    """渲染账户设置页面"""
    st.markdown("#### ⚙️ 账户设置")
    
    user_data = st.session_state.user_data
    email = user_data.get("email", "")
    
    # 修改密码
    st.markdown("##### 🔐 修改密码")
    
    with st.form("change_password_form"):
        old_password = st.text_input("原密码", type="password")
        new_password = st.text_input("新密码", type="password")
        confirm_password = st.text_input("确认新密码", type="password")
        
        if st.form_submit_button("🔄 修改密码", type="primary"):
            if old_password and new_password and confirm_password:
                if new_password != confirm_password:
                    st.error("两次输入的新密码不一致")
                elif len(new_password) < 6:
                    st.error("新密码长度至少6位")
                else:
                    user_manager = get_user_manager()
                    result = user_manager.change_password(email, old_password, new_password)
                    if result["success"]:
                        st.success("密码修改成功！")
                    else:
                        st.error(result["message"])
            else:
                st.warning("请填写完整信息")
    
    st.divider()
    
    # 账户信息
    st.markdown("##### 📋 账户信息")
    
    col1, col2 = st.columns(2)
    with col1:
        st.info(f"**用户ID：** {user_data.get('user_id', 'N/A')}")
        st.info(f"**用户名：** {user_data.get('username', 'N/A')}")
    with col2:
        st.info(f"**邮箱：** {email}")
        st.info(f"**注册时间：** 获取中...")
    
    # 删除账户（危险操作）
    st.markdown("##### ⚠️ 危险操作")
    
    with st.expander("🗑️ 删除账户", expanded=False):
        st.warning("⚠️ 删除账户将永久删除您的所有数据，此操作不可恢复！")
        
        if st.text_input("输入 'DELETE' 确认删除", key="delete_confirm") == "DELETE":
            if st.button("🗑️ 确认删除账户", type="primary"):
                st.error("账户删除功能开发中...")
        else:
            st.info("请输入 'DELETE' 来启用删除按钮")
